// 迭代器
pub fn run_example() {

    println!("借用迭代器:");
    let v1 = vec![1, 2, 3];
    let v1_iter = v1.iter();
    for val in v1_iter {
        println!("iter: {}", val);
    }

    println!("可变借用迭代器:");
    let mut v1_mut = vec![1, 2, 3];
    let v1_iter_mut = v1_mut.iter_mut();
    for val in v1_iter_mut {
        *val += 10;
        println!("iter_mut: {}", val);
    }

    println!("获取迭代器的所有权:");
    let v1_iter = v1.into_iter();
    for val in v1_iter {
        println!("into_iter: {}", val);
    }

    println!("map() 方法对迭代器中的每个元素应用一个函数:");
    let v1: Vec<i32> = vec![1, 2, 3];
    let doubled_vec: Vec<_> = v1.iter().map(|x| x * 2).collect();
    assert_eq!(doubled_vec, vec![2, 4, 6]);
    println!("doubled_vec: {:?}", doubled_vec);

    println!("filter() 方法根据一个函数的返回值来过滤迭代器中的元素:");
    let vec = vec![1, 2, 3, 4, 5];
    let even_vec: Vec<i32> = vec.iter().filter(|&x| x % 2 == 0).copied().collect();
    assert_eq!(even_vec, vec![2, 4]);
    println!("even_vec: {:?}", even_vec);

    println!("sum() 方法对迭代器中的所有元素进行求和 - 消耗迭代器:");
    let sum: i32 = vec.iter().sum();
    assert_eq!(sum, 15);
    println!("sum: {}", sum);
}